package com.example.test.poi;

import lombok.Cleanup;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.FileInputStream;

public class POIReadExcel {
    public static void main(String[] args) {
        test01();
    }

    /**
     * 读取xls文件
     **/
    @SneakyThrows
    private static void test01() {
        // 1. 获取文件输入流
        @Cleanup
        FileInputStream fis = new FileInputStream("D:\\tmp\\aaa.xls");
        // 2. 创建工作簿
        Workbook wb = new HSSFWorkbook(fis);
        // 3. 获取工作表
        Sheet sheet = wb.getSheetAt(0);
        // 4. 遍历获取所有行
        int rowCount = sheet.getPhysicalNumberOfRows();
        for (int rowNum = 0; rowNum < rowCount; rowNum++) {
            Row row = sheet.getRow(rowNum);
            StringBuilder stringBuilder = new StringBuilder();
            // 5. 遍历获取所有单元格
            int cellCount = row.getPhysicalNumberOfCells();
            for (int cellNum = 0; cellNum < cellCount; cellNum++) {
                Cell cell = row.getCell(cellNum);
                // 6. 判断单元格值类型
                int cellType = cell.getCellType();
                switch (cellType) {
                    case Cell.CELL_TYPE_NUMERIC:
                        stringBuilder.append(cell.getNumericCellValue()).append(" ");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        stringBuilder.append(cell.getStringCellValue()).append(" ");
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        stringBuilder.append("null").append(" ");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        stringBuilder.append(cell.getBooleanCellValue()).append(" ");
                        break;
                    default:
                        stringBuilder.append(cell.getErrorCellValue()).append(" ");
                }
            }
            System.out.println(stringBuilder.toString());
        }


    }
}
